import org.springframework.web.servlet.support.RequestContextUtils as RCU
import org.springframework.web.context.request.RequestContextHolder as RCH
import java.util.UUID
import Grole


class GuserController {
    
	def imageService

    static roleAccess =  [
            [action:"*", roles:["admin"]],
            [action:["sampleUpload","upload","logout","login","register","loginProcess","createProcess"], roles:["*"]],
	]


    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [ save:'POST', update:'POST']

    def list = {
        /**
         * do something here if you want to detect if the user is logged in or not
         */
        if(session?.user?.isLoggedIn()) {
          } else {
        }
        if(!params.max) params.max = 10
        [ guserList: Guser.list( params ) ]
    }

    def show = {
        def guser = Guser.get( params.id )

        if(!guser) {
            flash.message = "Guser not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ guser : guser ] }
    }

    def delete = {
        def guser = Guser.get( params.id )
        if(guser) {
            guser.delete()
            flash.message = "Guser ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = "Guser not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def guser = Guser.get( params.id )

        if(!guser) {
            flash.message = "Guser not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ guser : guser ]
        }
    }

    def update = {
        def user = Guser.get( params.id )
        if(user) {
            user.properties = params

		params.findAll{pm-> 
			pm.key.length()>2 && pm.key[0..2]=="otm"
		}.each {  p->
			def keys = p.key.split("_");
			def classkey = keys[1]
			def addtokeyorig = keys[2]
			def addtokey = 'addTo' + addtokeyorig[0].toUpperCase() + addtokeyorig[1..-1]
			classkey = classkey[0].toUpperCase() + classkey[1..-1]

		
			user."$addtokeyorig"= null

			p.value.each { val->
				def temp = Class.forName(classkey, true, grailsApplication.classLoader).newInstance()
				temp = temp.get(val)
				user."$addtokey"(temp)			
			} 
		}


            if(!user.hasErrors() && user.save()) {
                flash.message = "Guser ${params.id} updated"
                redirect(action:show,id:user.id)
            }
            else {
                render(view:'edit',model:[guser:user])
            }
        }
        else {
            flash.message = "Guser not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

/**
 * this will just show the login page
 * and a registration page
 *
 */
    def login = {
    }


/**
 * log out and redirect back to home page
 *
 */
    def logout = {
        session.user = new Guser()
        redirect(uri:"/")
    }






    def save = {
        def guser = new Guser(params)

        guser.activationCode = 'adminCreated'
        guser.activationDate = new Date()


        println "myroles = " + guser.roles



        
        if(guser) {
        
            params.findAll{pm-> 
                    pm.key.length()>2 && pm.key[0..2]=="otm"
            }.each {  p->
                    def keys = p.key.split("_");
                    def classkey = keys[1]
                    def addtokeyorig = keys[2]
                    def addtokey = 'addTo' + addtokeyorig[0].toUpperCase() + addtokeyorig[1..-1]
                    classkey = classkey[0].toUpperCase() + classkey[1..-1]
                    guser."$addtokeyorig"= null

                    p.value.each { val->
                        
                      def temp = Class.forName(classkey, true, grailsApplication.classLoader).newInstance()
                                println 'temp = ' + temp
                            temp = temp.get(val)
                            guser."$addtokey"(temp)
                    } 

                if(!guser.hasErrors() && guser.save()) {
                    flash.message = "Guser ${params.id} updated"
                    redirect(action:show,id:guser.id)
                }
                else {
                    render(view:'edit',model:[guser:guser])
                }
            }
        } else {
            flash.message = "Grole not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }


/**
 * process the create account request
 * if the username/password isn't correct, redirect back to the log in
 * screen with an error message in the flash scope
 * if successful, redirect back to home page, but with created user object in session
 *
 */
    def createProcess = {

        def u = Guser.findByNameOrEmail(params.username, params.email);

        if(u != null || params.username.trim()=='' ) {
          flash.messageCreate = "That username or email address is already in use."
          render(view:'register')
		return ''
        }
        if(params.password != params.confirm) {
              flash.messageCreate = "Your passwords don't match."
              render(view:'register')
            return ''
        }

        def r1 = Grole.findByName("default")
        def activationCode = UUID.randomUUID()
        def activationDate = new Date()

	def pr1 = new Gprofile(
		displayName:params.username,location:"",imageName:"none",
                homepageUri:"",
                address:"",
                city:"",
                state:"",
                country:"",
                postcode:"",
                phoneNumber:""
		).save()

        def user = new Guser(
            name:params.username,
            password:params.password,
            email:params.email,
            activationCode:"123",
		profile:pr1,
            activationDate:activationDate
            ).save();
        user.addToRoles(r1);
        user.save(flush:true);

        def messageSource = grailsAttributes.getApplicationContext().getBean("messageSource")
        def emailText = message(
            code:"grailskit.welcomeEmail",
            args:[grailsApplication.config.site.name, activationCode]
            )

      try {
        sendMail {
          to user.email
          from grailsApplication.config.gk.emailFrom
          subject "Welcome to " + grailsApplication.config.gk.site.name
          text emailText
        }

      } catch (Exception ex) {
        
      }
        user.loggedIn = true
        session.user = user
        redirect(grailsApplication.config.gk.defaultLocation)

    }


/**
 * process a request for a lost password via email
 *
 */
    def lostPassword = {

        def user = Guser.findByEmail(params.email)

        if(user==null) {
            flash.messageLost = "There was no account found for that email address"
            render(view:"login")
        } else {

          try {
            sendMail {
              to user.email
                  from grailsApplication.config.gk.emailFrom
              subject "Lost password for " + grailsApplication.config.site.name
              body "Your password is " + user.password
            }
          } catch (Exception ex) {

          }

          flash.messageLost = "Your password was sent to " + user.email
          render(view:"login")

	}

    }



/**
 * process the log in request
 * if the username/password isn't correct, redirect back to the log in
 * screen with an error message in the flash scope
 * if successful, redirect back to home page, but with created user object in session
 *
 */
    def loginProcess = {

        def u = Guser.findByNameAndPassword(params.username, params.password);

        if(u == null) {
          flash.message = "Error!"
          render(view:'login')
        } else {
// convert the 'roles' relationship (a PersistentSet)
// in to a List for the security filtering
            u.roleList = grailsApplication.config.gk.defaultRoles
            u.roles.each{ roleToCheck ->
                if(!u.roleList.contains(roleToCheck)) {
                    u.roleList.add(roleToCheck)
                }
            }
            u.save(flush:true)
            u.loggedIn = true
            session.user = u

            if(session.gk) {
                redirect(
                    controller:session.gk.redirectTo.controller,
                    action: session.gk.redirectTo.action
                    )
            } else {
                redirect( grailsApplication.config.gk.defaultLocation )
	    }
       	}
    }

	/**
	 * show the register page
	 */
	def register = { }


      /**
       * sample upload form
       */
      def sampleUpload = {
		println grailsApplication.config.basepath
	}

	def upload = {
		def baseWebPath = RCH.requestAttributes.servletContext.getRealPath('/')
		def file = params['myFile']
		imageService.upload(file)
	}
      /**
       * upload process
       */
	def upload2 = {
		def baseWebPath = RCH.requestAttributes.servletContext.getRealPath('/')
		def file = params['myFile']


		println baseWebPath+'images/'+file.getOriginalFilename()
		def imPath = grailsApplication.config.gk.imageMagickPath
		def tnQuality = grailsApplication.config.gk.thumbnail.quality
		def tnX = grailsApplication.config.gk.thumbnail.x
		def tnY = grailsApplication.config.gk.thumbnail.y

		if(!file?.empty) {
			def pathAndFileOrig = baseWebPath + 'images/' + file.getOriginalFilename()
			def pathAndFileThumb= baseWebPath + 'images/foo.thumb.png'
			file.transferTo(new File(pathAndFileOrig) )
			if(imPath!='') {
				def command = imPath + " -quality " + tnQuality
				command += " -scale " + tnX + "x" + tnY + " "
				command += pathAndFileOrig
				command += " " + pathAndFileThumb
println command
// do the thumbnailing with imagemagick
				def proc = Runtime.getRuntime().exec(command)
				def status = 0
				while(true) {
					try {
						status = proc.waitFor()
						break
					} catch (Exception e) {
						println e
					}
				}
			} else {
// if we don't have imagemagick installed, make the original file the
// thumbnail as well (suboptimal but won't throw any errors then)
			file.transferTo(new File(pathAndFileThumb) )

			}
		}
      }

}
